package org.example.videotran.service;

import org.example.videotran.pojo.LanguageChoose;
import org.example.videotran.pojo.TransVideo;
import org.example.videotran.utils.FileUtils;
import org.example.videotran.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

@Service
public class VideoService implements IVideoService{

    private final String baseUrl = "http://127.0.0.1:9011";
    @Value("${file.upload-dir}")
    private String uploadPath;

    RestTemplate restTemplate = new RestTemplate();

    @Override
    public ResponseEntity<String> translate_srt(MultipartFile file, String target_language, String source_code) {
        try {

            FileUtils.upload(file,uploadPath);

            // 2. 设置请求头（包含 Bearer Token）
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json"); // 设置正确的 Content-Type
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            String jsonBody = "";

            if (source_code != null){
                jsonBody = "{"
                        + "\"name\": \"" + uploadPath + file.getOriginalFilename() +"\","
                        + "\"translate_type\": \"" + 1 + "\","
                        + "\"target_language\": \""+ target_language +"\","
                        + "\"source_code\": \""+ source_code +"\""
                        + "}";
            }else {
                jsonBody = "{"
                        + "\"name\": \"" + uploadPath + file.getOriginalFilename() +"\","
                        + "\"translate_type\": \"" + 1 + "\","
                        + "\"target_language\": \""+ target_language +"\""
                        + "}";
            }

            // 3. 构建 HttpEntity
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody,headers);

            // 4. 发送 GET 请求并获取响应
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl + "/translate_srt",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<String> recogn(MultipartFile video, LanguageChoose languageChoose) {
        try {

            String upload = FileUtils.upload(video, uploadPath).replace("\\","/");

            // 2. 设置请求头（包含 Bearer Token）
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json"); // 设置正确的 Content-Type
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            String jsonBody = "{"
                    + "\"name\": \"" + upload +"\","
                    + "\"recogn_type\": \"" + 0 + "\","
                    + "\"model_name\": \"" + "tiny" + "\","
                    + "\"detect_language\": \"" + languageChoose.getTarget_language() + "\","
                    + "\"split_type\": \"" + languageChoose.getSplit_type() + "\""
                    + "}";

            System.out.println(jsonBody);

            // 3. 构建 HttpEntity
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody,headers);

            // 4. 发送 GET 请求并获取响应
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl + "/recogn",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<String> taskStatus(String taskId) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json"); // 设置正确的 Content-Type
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            String jsonBody = "{"
                    + "\"task_id\": \"" + taskId +"\""
                    + "}";

            System.out.println(jsonBody);

            // 3. 构建 HttpEntity
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody,headers);

            // 4. 发送 GET 请求并获取响应
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl + "/task_status",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<String> transVideo(MultipartFile video, TransVideo transVideo) {
        try {

            String upload = FileUtils.upload(video, uploadPath).replace("\\","/");

//            transVideo.setName(upload);
            transVideo.setName(upload);
            transVideo.setRecogn_type(0);
            transVideo.setModel_name("tiny");
            transVideo.setTranslate_type(1);
            transVideo.setTts_type(0);

            // 2. 设置请求头（包含 Bearer Token）
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json"); // 设置正确的 Content-Type
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            String jsonBody = JsonUtils.objectToJson(transVideo);

            System.out.println(jsonBody);

            // 3. 构建 HttpEntity
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody,headers);

            // 4. 发送 POST 请求并获取响应
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl + "/trans_video",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<byte[]> downloadDocument(String documentPath) {

        // 1. 解析文件路径
        Path path = Paths.get(documentPath);

        System.out.println(path);

        System.out.println(Files.exists(path));

        // 2. 检查文件是否存在
        if (!Files.exists(path)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        // 3. 读取文件内容到字节数组
        byte[] fileContent = null;
        try {
            fileContent = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 4. 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData(
                "attachment",
                URLEncoder.encode(path.getFileName().toString(), StandardCharsets.UTF_8).replaceAll("\\+", "%20")
        );

        // 5. 返回字节数组和响应头
        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }
}
